using System;
using System.Threading;

namespace MonoNZB.NNTP
{
	public class Connection
	{
		public bool Connected { get; set; }
		public string Status { get; set; }
		public string Message { get; set; }
		
		private Thread _thread;
		private Client _client;
		private Server _server;
		
		public Connection (Server Server)
		{
			_server = Server;
			
			Status = "Disconnected";
			Message = string.Empty;
		}
		
		public void Connect()
		{
			if (Connected)
			{
				return;	
			}
			
			try
			{
				_thread = new Thread(new ThreadStart(ThreadRun));
				_thread.Start();
			} 
			catch
			{
				Connected = false;	
			}
		}
		
		public void Disconnect()
		{
			if (!Connected)
			{
				return;	
			}
			
			Status = "Disconnected";
			Connected = false;
		}
		
		private void ThreadRun()
		{
			try
			{
				_client = new Client();
				
				Status = "Connected";
				
				if (_server.Username != string.Empty && _server.Password != string.Empty)
				{
					Status = "Authenticating";
					_client.Authenticate();			
				}
				
				Connected = true;
				Status = "Connected";
			}
			catch (Exception e)
			{
				Status = "Disconnected";
				Message = e.Message;
				
				Connected = false;
				return;
			}
			
			while (Connected && _client.Connected)
			{
				Process();	
			}
			
			if (_client.Connected)
			{
				try
				{
					_client.Close();	
				}
				catch
				{
				}
			}
			
			Status = "Disconnected";
			Connected = false;
		}
		
		private void Process()
		{
			Status = "Idle";	
		}
	}
}
